package cn.wolfcode.crud.service.impl;

import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.mapper.EmployeeMapper;
import cn.wolfcode.crud.qo.PageResult;
import cn.wolfcode.crud.qo.QueryObject;
import cn.wolfcode.crud.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    public void save(Employee employee, Long[] ids) {


        //对密码加密(吧用户名作为盐)
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(),employee.getName());
        //重新设置一下员工的密码
        employee.setPassword(md5Hash.toString());
        employeeMapper.insert(employee);

        //处理中间表
        if(ids!=null&&ids.length>0){
                employeeMapper.insertRelation2(employee.getId(),ids);
        }
    }

    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        //删除中间表关系
        employeeMapper.deleteRelation(id);
    }

    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除中间表关系
        employeeMapper.deleteRelation(employee.getId());
        //再添加新的关系
        if(ids!=null&&ids.length>0){
            employeeMapper.insertRelation2(employee.getId(),ids);
        }
    }

    @Transactional(readOnly = true)
    public Employee get(Long id) {
        Employee employee= employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Transactional(readOnly = true)
    public List<Employee> listAll() {
        List<Employee> employee = employeeMapper.selectAll();
        return employee;
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
       List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
       Employee employee = employeeMapper.selectByUserNameAndPassword(username,password);
       if(employee == null){
           throw new RuntimeException("账户或密码错误");
       }
        return employee;
    }

    @Override
    public Employee selectPassword(Long id,String oldPassword) {
        //先拿到老员工的密码
        Employee employee1 = employeeMapper.selectByPrimaryKey(id);
        //对密码加密(吧用户名作为盐)
        Md5Hash md5Hash = new Md5Hash(oldPassword,employee1.getName());
        //重新设置一下员工的密码
        employee1.setPassword(md5Hash.toString());

        Employee employee = employeeMapper.selectByPassword(id,employee1.getPassword());
        if (employee==null){
            throw  new RuntimeException("原密码错误");
        }
        return employee;
    }

    @Override
    public void updatePassword(Long id,String newPassword) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        //对密码加密(吧用户名作为盐)
        Md5Hash md5Hash = new Md5Hash(newPassword,employee.getName());
        //重新设置一下员工的密码
        employee.setPassword(md5Hash.toString());
        employeeMapper.updateByPassword(id,employee.getPassword());

    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {

        return  employeeMapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        
        //先去数据库查所有员工的信息
        List<Employee> employees = employeeMapper.selectAll();

        //创建03的excel文件
        Workbook wb = new HSSFWorkbook();

        //创建一个表
        Sheet sheet = wb.createSheet("员工通讯录");

        //创建一个标题,给用户看
        Row row = sheet.createRow(0);
        //第0行第0个数据
        row.createCell(0).setCellValue("姓名");
        //第1行第1个数据
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        //循环员工集合
        for (int i = 0; i <employees.size() ; i++) {
            //拿到每个员工
            Employee employee = employees.get(i);

            //第1行
            row = sheet.createRow(i+1);
            //第1行第1个数据
            row.createCell(0).setCellValue(employee.getName());
            //第1行第1个数据
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());



        }


        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一张表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            //判断如果用户名是空，就不再往下读
            if(!StringUtils.hasLength(name.trim())){
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());

            //判断age是什么类型的
            CellType type = row.getCell(2).getCellType();
            //如果是字符串,就把第二行的值转换成int封装进age
            if (type.equals(type.STRING)){
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            }else {
                employee.setAge((int)(row.getCell(2).getNumericCellValue()));
            }


            //设置默认密码1
            employee.setPassword("1");
            //调用保存方法,加密保存到数据库
            this.save(employee,null);
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRolesn(sns);
    }
}
